export * from './interface'
export * from './ask'

/**
 * Axios封装
 */
import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios'

const config: AxiosRequestConfig = {
  // 请求基准路径
  baseURL: import.meta.env.VITE_API_URL,
  // 超时时间
  timeout: 1000 * 10
}

class Request {
  // 类型
  service: AxiosInstance
  constructor(config: AxiosRequestConfig) {
    // 创建axios实例
    this.service = axios.create(config)

    // 请求拦截器
    this.service.interceptors.request.use((config) => {
      return config
    })

    // 响应拦截器
    this.service.interceptors.response.use(
      (response): any => {
        const { data, headers } = response
        // 拿到数据总条数
        const totalCount = +headers['x-total-count']
        return { data, totalCount }
      },
      (error) => {
        return Promise.reject(error)
      }
    )
  }
  // get请求
  get<T>(url: string, params?: object | string | number, _object = {}): Promise<T> {
    return this.service.get(`/${url}`, { params, ..._object })
  }

  // post请求 - 添加数据用[用户注册，购物车添加]
  post<T>(url: string, params?: object | string | number, _object = {}): Promise<T> {
    return this.service.post(`/${url}`, { params, ..._object })
  }
}

export default new Request(config)
